package 算法;

/**
 * @author 乐心湖
 * @date 2020/6/15 22:42
 **/
public class LongestCommonPrefix {

    public static String longestCommonPrefix1(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        String s = strs[0];
        for (int i = 1; i < strs.length; i++) {
            int index = 0;
            while (
                    index < (Math.min(s.length(),strs[i].length()))
                            && s.charAt(index) == strs[i].charAt(index)
            ){
                index++;
            }
            s = strs[i].substring(0, index);
            if(s.length() == 0){
                return s;
            }
        }
        return s;
    }

    public String longestCommonPrefix2(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String s = strs[0];
        for (int i = 1; i < strs.length; i++) {
            while(!strs[i].startsWith(s)){
                s = s.substring(0, s.length()-1);
            }
        }
        return s;
    }
}
